import { onUnmounted } from "vue";
import { tinymceEditorConfig } from "@/views/formgen/components/tinymce/config";
import loadTinymce from "@/views/formgen/utils/loadTinymce";

export function useItemTinymceHook(handleChangeHtml: Function) {
  const itemTinymceConfig = {
    ...tinymceEditorConfig,
    inline: true,
    contextmenu: false,
    menubar: false,
    body_class: "qr-tinymce-inline",
    toolbar:
      "  fontsize bold italic underline strikethrough  removeformat alignleft aligncenter alignright  subscript superscript  hr forecolor backcolor image   formvariable popup fulledit ",
    extended_valid_elements: "formvariable[*]",
    custom_elements: "formvariable[*]",
    init_instance_callback: (editor: any) => {
      editor.on("blur", () => {
        editor.save();
        handleChangeHtml(editor.id, editor.getContent());
      });
    },
    setup: (editor: any) => {
      console.log(editor);
    }
  };

  // 销毁富文本编辑器
  onUnmounted(() => {
    destroyAllTinymce();
  });

  // 销毁当前当前页全部
  const destroyAllTinymce = () => {
    if (window.tinymce) {
      try {
        window.tinymce!.remove(".editor");
      } catch (e) {}
    }
  };

  /**
   * 初始化多个富文本编辑器
   */
  const initTinymce = (vModel: string, callback: Function) => {
    console.log(` selector: .${vModel} .editor"`);
    loadTinymce((tinymceObj: any) => {
      tinymceObj
        .init({
          ...itemTinymceConfig,
          selector: `.${vModel} ` + " .editor"
        })
        .then((editors: any) => {
          console.log("init success", editors);
          callback(editors);
        })
        .catch((err: any) => {
          console.log("init error", err);
        });
    });
  };

  /**
   * 销毁富文本编辑器
   * @param id
   */
  const destroyTinymceEditor = (id: string) => {
    window.tinymce.get(id).destroy();
  };

  /**
   * 创建富文本编辑器
   * @param id
   * @param tinymceConfig
   */
  const createTinymceEditor = (id: string, tinymceConfig?: any) => {
    const editor = window.tinymce.createEditor(id, tinymceConfig || itemTinymceConfig);
    editor.render();
  };

  return {
    destroyTinymceEditor,
    createTinymceEditor,
    initTinymce,
    destroyAllTinymce
  };
}
